﻿using Microsoft.EntityFrameworkCore;
namespace EMall.Uow
{
    public class EfCoreUnitOfWork<TDbContext> : UnitOfWork 
        where TDbContext : DbContext
    {
        protected TDbContext _dbContext;
        public EfCoreUnitOfWork(
            TDbContext dbContext)
        {
            ArgumentNullException.ThrowIfNull(dbContext, nameof(dbContext));
            _dbContext = dbContext;
        }
        public override async Task BeginAsync()
        {
            await _dbContext.Database.BeginTransactionAsync();
        }
        public override async Task OnCommitExecutingAsync()
        {
            await Task.CompletedTask;
        }
        public override async Task OnCommitAsync()
        {
            await _dbContext.Database.CommitTransactionAsync();
        }
        public override async Task OnCommitExecutedAsync()
        {
            await Task.CompletedTask;
        }
        public override async Task RollbackAsync()
        {
            if (_dbContext.Database.CurrentTransaction is not null)
            {
                await _dbContext.Database.RollbackTransactionAsync();
            }
        }
        public override void Dispose()
        {
            _dbContext.Dispose();
        }
    }
}
